package cn.udrm.water.base.v1.manager.restful;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.udrm.water.base.v1.commons.models.ResponseParam;
import cn.udrm.water.base.v1.commons.models.ZTreeNodeVo;
import cn.udrm.water.base.v1.manager.dto.BaseResourceDto;
import cn.udrm.water.base.v1.manager.service.BaseResourceService;

/**
 * 资源对外接口
 * @author liukang
 * @date 2019年4月1日
 */
@RestController
@RequestMapping(value="v1/restful/resource")
public class BaseResourceRestful {
	@Autowired
	private BaseResourceService resourceService;
	
	@PostMapping(value="save")
	public ResponseParam<BaseResourceDto> save(@RequestBody BaseResourceDto dto) {
		BaseResourceDto save = resourceService.save(dto);
		return new ResponseParam<BaseResourceDto>("数据保存成功", 200, save);
	}
	
	@PostMapping(value="update")
	public ResponseParam<BaseResourceDto> update(@RequestBody BaseResourceDto dto) {
		BaseResourceDto update = resourceService.update(dto);
		return new ResponseParam<BaseResourceDto>("数据保存成功", 200, update);
	}
	
	@PostMapping(value="getWithChildrens")
	public ResponseParam<List<ZTreeNodeVo>> getWithChildrens(@RequestParam(value="id") String id, @RequestParam(value="type") String type) {
		BaseResourceDto withChildrensById = resourceService.getWithChildrensById(id);
		if (withChildrensById != null) {
			List<BaseResourceDto> childrenDtos = withChildrensById.getChildrenDtos();
			List<ZTreeNodeVo> list = new ArrayList<ZTreeNodeVo>();
			if (childrenDtos != null) {
				childrenDtos.forEach((r) -> {
					list.add(new ZTreeNodeVo(r.getId(), r.getName(), id, ""));
				});
			}
			return new ResponseParam<List<ZTreeNodeVo>>("数据获取成功", 200, list);
		}
		return new ResponseParam<>("数据获取失败", 501);
	}
	
	@GetMapping(value="getWithRolesById/{id}")
	public ResponseParam<BaseResourceDto> getWithRolesById(@PathVariable(value="id") String id) {
		BaseResourceDto withChildrensById = resourceService.getWithRolesById(id);
		return new ResponseParam<BaseResourceDto>("数据获取成功", 200, withChildrensById);
	}
	

	@GetMapping(value="getResourcesTree")
	public ResponseParam<List<ZTreeNodeVo>> getResourcesTree() {
		List<ZTreeNodeVo> resourcesTree = resourceService.getResourcesTree();
		return new ResponseParam<List<ZTreeNodeVo>>("数据获取成功", 200, resourcesTree);
	}
}
